<template>
  <div class="register-page">
    <van-nav-bar title="注册" left-arrow @click-left="$router.back()" />
    <van-popup
      style="min-height: 30%; width: 100%; z-index: 20003;background: #f1f1f1;overflow: hidden;"
      v-model="showpop"
    >
      <div class="slideverify" v-if="showpop">
        <!-- <SlideVerify ref="slideblock" @success="sendSmsCode"></SlideVerify> -->
        <div id="verifyCodeDemo">
          <p id="picyzm" style="margin:10px"></p>
          <div style="text-align:center;margin-bottom:5px;margin-right:10px;">点击图片刷新</div>
          <van-field
            autocomplete="off"
            v-model="picyzmValue"
            style="text-align:center;"
            placeholder="请输入4位验证码"
          />
          <div style="text-align: center;">
            <van-button style="margin:10px;width:65px;" size="small" @click="showpop = false">取消</van-button>
            <van-button style="margin:10px;width:65px;" size="small" type="info" @click="handleVerify()"
              >验证</van-button
            >
          </div>
        </div>
      </div>
    </van-popup>
    <van-image width="100%" :src="registerImg" fit="cover" />
    <van-divider :style="{color: '#323233', borderColor: '#1989fa', padding: '0 88px', fontWeight: 'bold'}"
      >新用户注册</van-divider
    >
    <van-form>
      <van-field
        autocomplete="off"
        clearable
        required
        v-model="username"
        type="number"
        name="account"
        label="手机号"
        placeholder="请输入手机号"
        maxlength="11"
        :rules="[
          {
            required: true,
            message: '请填写手机号'
          }
        ]"
      />
      <van-field
        autocomplete="off"
        required
        clearable
        v-model="password"
        :type="isShowPwd1 ? 'text' : 'password'"
        name="password"
        label="密码"
        placeholder="请输入密码"
        :rules="[{required: true, message: '请填写密码'}]"
        :right-icon="isShowPwd1 ? 'eye-o' : 'closed-eye'"
        @click-right-icon="isShowPwd1 = !isShowPwd1"
      />
      <van-field
        autocomplete="off"
        required
        clearable
        v-model="confirmPwd"
        :type="isShowPwd2 ? 'text' : 'password'"
        name="confirmPwd"
        label="确认密码"
        placeholder="请再次输入密码"
        :rules="[{required: true, message: '请再次填写密码'}]"
        :right-icon="isShowPwd2 ? 'eye-o' : 'closed-eye'"
        @click-right-icon="isShowPwd2 = !isShowPwd2"
        :error-message="isSamePwd ? '' : '前后密码不一致'"
      />
      <van-field
        autocomplete="off"
        v-model="parentId"
        name="parentId"
        label="推荐人的ID"
        placeholder="不需要填写"
        readonly
      />
      <van-field
        autocomplete="off"
        v-model="source_channel_name"
        name="source_channel_name"
        label="注册渠道名称"
        placeholder="不需要填写"
        readonly
      />
      <van-field
        autocomplete="off"
        v-model="source_type_name"
        name="source_type_name"
        label="注册来源类型"
        placeholder="不需要填写"
        readonly
      />
      <van-field
        autocomplete="off"
        v-model="sms"
        center
        required
        clearable
        label="短信验证码"
        name="code"
        placeholder="请输入短信验证码"
      >
        <template #button>
          <van-button v-show="showcount" size="small" type="info" :disabled="disabledStatus" @click="sendCode(1)"
            >发送验证码</van-button
          >
          <van-button v-show="!showcount" size="small" type="info" disabled @click="sendCode(1)"
            >{{ count }} s</van-button
          >
        </template>
      </van-field>

      <div style="margin: 16px;">
        <van-checkbox v-model="checked" :bind-group="false" style="margin:0 0 10px 10px;">
          <u @click.stop="userAgreement" style="color: #1989fa">用户注册协议</u> 和
          <u @click.stop="privacyAgreement" style="color: #1989fa ">用户隐私协议</u>
        </van-checkbox>
        <van-button round block type="info" native-type="submit" :class="{submit: !checked}" @click="onSubmit"
          >提交</van-button
        >

        <van-button
          style="margin-top:20px"
          round
          block
          type="primary"
          color="#29A1F7"
          native-type="submit"
          @click="onLogin"
          >已注册过，去登录</van-button
        >
        <van-popup round :close-on-click-overlay="false" v-model:show="showPopup" bind:close="onClose">
          <!-- <verCode ref="slideblock" @popFUNC="popFUNC"></verCode> -->
          <slide-verify
            :l="42"
            :r="10"
            :w="210"
            :h="155"
            @success="onSuccess"
            @fail="onFail"
            @refresh="onRefresh"
            slider-text="向右滑动"
          ></slide-verify>
        </van-popup>
      </div>
    </van-form>

    <com-download></com-download>
  </div>
</template>

<script>
import {Toast} from 'vant'
import SlideVerify from '@/components/slideImg' //引入
import verCode from '@/components/verCode' //引入
import logoImg from '@/assets/logo.png'
import registerImg from '@/assets/img/registerImg.png'
import {GVerify} from '@/utils/gVerify.js'
import androidImg from '@/assets/img/register/android.png'
import iosImg from '@/assets/img/register/ios.png'

import comDownload from '../welcome/comDownload'
import router from '../../router'

export default {
  name: 'register',
  components: {
    verCode,
    SlideVerify, //注册组件
    comDownload
  },

  data() {
    return {
      showPopup: false,
      isShowSlide: false,
      showpop: false,
      showcount: true,
      timer: null,
      count: '',
      isShowPwd1: false,
      checked: false,
      isShowPwd2: false,
      isSamePwd: true,
      registerImg,
      username: '',
      password: '',
      confirmPwd: '',
      sms: '',
      // 推荐人id
      parentId: '',
      /*
       * 2022-03-01 新的需求
       * 渠道id,
       * 渠道名,
       * 来源类型,
       * */
      source_channel_id: '',
      source_channel_name: '',
      source_type: '',
      source_type_name: '',

      disabled: true,
      androidImg: logoImg,
      iosImg: logoImg,
      web_url: '',
      iosLink: '',
      appLik: '',
      verifyCode: null,
      picyzmValue: ''
    }
  },
  created() {
    var startX, startY
    document.addEventListener('touchstart', function(e) {
      startX = e.targetTouches[0].pageX
      startY = e.targetTouches[0].pageY
    })
    document.addEventListener(
      'touchmove',
      function(e) {
        var moveX = e.targetTouches[0].pageX
        var moveY = e.targetTouches[0].pageY

        if (Math.abs(moveX - startX) > Math.abs(moveY - startY)) {
          e.preventDefault()
        }
      },
      {passive: false}
    )
    // 生命周期中第一次拿到this
    if (this.$route.query.recommendID) {
      const {recommendID, source_channel_id, source_channel_name, source_type} = this.$route.query
      this.parentId = recommendID
      this.source_channel_id = source_channel_id
      this.source_channel_name = source_channel_name
      this.source_type = source_type

      // 路径
      const sourceTypeObj = {
        L: '网址链接',
        V: '竖版海报',
        H: '横版海报'
      }
      this.source_type_name = sourceTypeObj[source_type]
    }
  },

  computed: {
    disabledStatus() {
      let result
      if (this.username && this.password && this.confirmPwd) {
        if (this.password != this.confirmPwd) {
          /*Toast({
              message: "前后密码不一致",
              position: 'bottom',
              duration: 100
            });*/
          this.isSamePwd = false
          result = this.disabled
        } else {
          result = !this.disabled
          this.isSamePwd = true
        }
      } else {
        result = this.disabled
      }
      return result
    }
  },
  methods: {
    //验证码
    creatGVerify() {
      //初始化验证码
      this.verifyCode = new GVerify({
        id: 'picyzm',
        type: 'blend'
      })
    },
    handleVerify() {
      var res = this.verifyCode.validate(this.picyzmValue)
      if (res) {
        this.sendSmsCode()
      } else {
        alert('验证码错误')
      }
    },
    hideSlide() {
      setTimeout(() => {
        this.isShowSlide = false
      }, 500)
    },
    sendSmsCode() {
      setTimeout(() => {
        this.showpop = false
        this.getQode()
      }, 500)
    },
    async getQode() {
      // 请求参数
      const TIME_COUNT = 60

      const params = {phone: this.username, type: 1}
      console.log('aaaaaa')
      const res = await this.$api.user.reqSendCode(params)

      if (res.code === 200) {
        Toast(res.data)
        if (!this.timer) {
          this.count = TIME_COUNT
          this.showcount = false

          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--
            } else {
              this.showcount = true
              clearInterval(this.timer)
              this.timer = null
            }
          }, 1000)
        }
      } else {
        Toast(res.msg)
      }
    },
    userAgreement() {
      this.$router.push('/userAgreement')
    },
    onLogin() {
      this.$router.push('/login')
    },
    privacyAgreement() {
      this.$router.push('/privacyAgreement')
    },
    async onSubmit() {
      if (!this.checked) {
        Toast('请阅读并勾选用户协议！')
      } else {
        if (this.username && this.password && this.confirmPwd && this.password === this.confirmPwd && this.sms) {
          const params = {
            account: this.username,
            password: this.$Base64.encode(this.$md5(this.password) + this.$md5('jinpin888')),
            code: this.sms,
            parentid: this.parentId,
            source_channel_id: this.source_channel_id,
            source_type: this.source_type
          }
          const res = await this.$api.user.reqRegister(params)
          if (res.code === 200) {
            Toast(res.data)
            await this.$router.push({
              path: '/login'
              // 这块不能携带，否则出现逻辑死循环。
              /*query: {
                redirect: this.$router.currentRoute.fullPath
              }*/
            })
          } else {
            Toast(res.msg)
          }
        } else {
          Toast('必填内容没有输入, 请检查输入框内容')
        }
      }
    },

    // async sendCode(index) {
    //   let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
    //   if (!myreg.test(this.username)) {
    //     Toast('号码格式错误')
    //     this.username.focus
    //     console.log(this.username)
    //     return
    //   }
    //   this.showpop = true
    //   this.isShowSlide = true
    //   this.verifyCode = null
    //   this.$nextTick(() => {
    //     this.creatGVerify()
    //   })
    // }

    sendCode(index) {
      let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (!myreg.test(this.username)) {
        Toast('号码格式错误')
        this.username.focus
        console.log(this.username)
        return
      }
       this.getQode()
      // this.showPopup = true
    },
    popFUNC() {
      this.showPopup = false
      this.getQode()
    },
    onSuccess() {
      this.showPopup = false
      this.getQode()
    }
  }
}
</script>

<style lang="scss" scoped>
.register-page {
  width: 100%;
  touch-action: none;
  touch-action: pan-y;
  .web_app {
    position: relative;
    height: 90px;
    .web_img {
      width: 100%;
      vertical-align: bottom;
    }
    .name {
      top: 56px;
      position: absolute;
      left: 0;
      right: 0;
      text-align: center;
      margin: 0 auto;
      color: #ffffff;
      font-size: 16px;
    }
  }
  .submit {
    background: #e9e9e9;
    color: #cecece;
    border: 0;
    margin-bottom: 20px;
  }
  .alignment {
    text-align: justify;
    text-justify: newspaper;
    word-break: break-all;
    font-size: 10px;
  }
  .bottom {
    display: flex;
    justify-content: space-around;
  }
  .tip {
    box-sizing: border-box;
    padding: 0 10px;
    font-size: 15px;
    .desc {
      margin-bottom: 20px;
      line-height: 1.33em;
      letter-spacing: 1.6px;
      text-align: justify;
    }
    .tip_link {
      margin-bottom: 36px;
    }
  }
}
</style>
